<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Files;


use Selibra\Tools\Tools;

class Read
{

    /**
     * @var Rule
     */
    protected Rule $rule;


    /**
     * @var array
     */
    protected $dirs;


    public function __construct(Rule $rule)
    {
        $this->rule = $rule;
    }


    /**
     * @param Rule $rule 读取规则
     * @param bool $through 是否遍历读取下级所有目录
     * @param bool $returnFileTree 是否以文件树状返回
     * @return array
     */
    public function files($through = false, $returnFileTree = true)
    {
        $path = realpath($this->rule->getPath());
        $files = glob($path . '/' . $this->rule->getPrefix() . '*' . $this->rule->getSuffix());
        $this->dirs = glob($path . '/*', GLOB_ONLYDIR);
        $files = array_diff($files, $this->dirs);
        if ($through) {
            /**
             * 深度拷贝rule对象
             * @var Rule $rule
             */
            $rule = Tools::deepCopyObject($this->rule);
            foreach ($this->dirs as $dir) {
                if( $this->rule->getIgnore()->exist($dir) ){
                    continue;
                }
                $rule->setPath($dir);
                $read = new Read($rule);
                $throughFiles = $read->files($through);
                foreach ($throughFiles as $file) {
                    array_push($files, $file);
                }
            }
        }
        return $files;
    }


    /**
     * @param bool $through
     * @return array
     */
    public function dirs($through = false)
    {
        if( !isset($this->dirs) ){
            $path = realpath($this->rule->getPath());
            $this->dirs = glob($path . '/*', GLOB_ONLYDIR);
        }
        return $this->dirs;
    }

}